package com.jack.charging.order.config;

import com.jack.charging.order.common.MqttConstants;
import com.jack.charging.order.mqtt.MqttConsumer;
import com.jack.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Jack
 * @date 2025/2/11 11:50
 * @see
 * @since
 */
@Configuration
public class MqttConfiguration {
    @Autowired
    private MqttContext mqttContext;
    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    private final String  host = "tcp://127.0.0.1:1883";
    private final String userName = "admin";
    private final String password = "public";
    private final String clientId = "order_service_client"+Math.random();



    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient mqttClient = new MqttClient(host, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(userName);
        options.setPassword(password.toCharArray());

        MqttConsumer constants = new MqttConsumer(mqttClient, mqttContext);
        mqttClient.setCallback(constants);
        mqttClient.connect(options);
        log.debug("mqtt client connect success");
        return mqttClient;
    }
}
